#!/usr/bin/env python3
"""
OBS Studio 视频播放控制示例脚本
"""

import json
import os
import sys
import time
from src.obs_client import OBSClient
from src.video_controller import VideoController


def load_config():
    """加载配置文件"""
    config_path = os.path.join(os.path.dirname(__file__), 'config', 'obs_config.json')
    with open(config_path, 'r', encoding='utf-8') as f:
        return json.load(f)


def main():
    """主函数"""
    # 加载配置
    config = load_config()
    obs_config = config['obs_websocket']
    
    # 创建OBS客户端
    with OBSClient(
        host=obs_config['host'],
        port=obs_config['port'],
        password=obs_config['password']
    ) as obs_client:
        
        if not obs_client.is_connected():
            print("错误: 无法连接到OBS Studio")
            print("请确保:")
            print("1. OBS Studio正在运行")
            print("2. obs-websocket插件已安装并启用")
            print("3. WebSocket服务器已启动")
            return
        
        # 创建视频控制器
        video_controller = VideoController(obs_client)
        
        # 获取当前场景
        current_scene = obs_client.get_current_scene()
        print(f"当前场景: {current_scene}")
        
        # 获取媒体源列表
        media_sources = video_controller.get_media_sources(current_scene)
        if not media_sources:
            print("错误: 当前场景中没有媒体源")
            print("请在OBS Studio中添加媒体源并指定视频文件")
            return
        
        print(f"找到媒体源: {media_sources}")
        
        # 选择要控制的媒体源
        if len(media_sources) == 1:
            source_name = media_sources[0]
            print(f"使用媒体源: {source_name}")
        else:
            print("多个媒体源可用:")
            for i, source in enumerate(media_sources):
                print(f"{i + 1}. {source}")
            
            while True:
                try:
                    choice = int(input("请选择媒体源编号: ")) - 1
                    if 0 <= choice < len(media_sources):
                        source_name = media_sources[choice]
                        print(f"已选择: {source_name}")
                        break
                    else:
                        print("无效的选择，请重试")
                except ValueError:
                    print("请输入数字")
        
        # 交互式控制
        print("\n=== 视频播放控制 ===")
        print("命令:")
        print("  play    - 播放视频（从头开始）")
        print("  pause   - 暂停视频")
        print("  resume  - 恢复播放")
        print("  stop    - 停止视频")
        print("  show    - 显示视频")
        print("  hide    - 隐藏视频")
        print("  status  - 查看状态")
        print("  sources - 列出所有媒体源")
        print("  switch  - 切换媒体源")
        print("  quit    - 退出")
        
        while True:
            try:
                command = input("\n请输入命令: ").strip().lower()
                
                if command == 'play':
                    video_controller.play_video(source_name)
                    
                elif command == 'pause':
                    video_controller.pause_video(source_name)
                    
                elif command == 'resume':
                    video_controller.resume_video(source_name)
                    
                elif command == 'stop':
                    video_controller.stop_video(source_name)
                    
                elif command == 'show':
                    video_controller.set_video_visibility(source_name, True)
                    
                elif command == 'hide':
                    video_controller.set_video_visibility(source_name, False)
                    
                elif command == 'status':
                    status = video_controller.get_media_status(source_name)
                    if status:
                        print(f"媒体状态: {status}")
                    else:
                        print("无法获取媒体状态")
                        
                elif command == 'sources':
                    current_sources = video_controller.get_media_sources()
                    if current_sources:
                        print("当前媒体源:")
                        for i, source in enumerate(current_sources):
                            marker = " <- 当前" if source == source_name else ""
                            print(f"{i + 1}. {source}{marker}")
                    else:
                        print("没有找到媒体源")
                        
                elif command == 'switch':
                    current_sources = video_controller.get_media_sources()
                    if len(current_sources) > 1:
                        print("可用媒体源:")
                        for i, source in enumerate(current_sources):
                            marker = " <- 当前" if source == source_name else ""
                            print(f"{i + 1}. {source}{marker}")
                        
                        try:
                            choice = int(input("请选择新的媒体源编号: ")) - 1
                            if 0 <= choice < len(current_sources):
                                source_name = current_sources[choice]
                                print(f"已切换到: {source_name}")
                            else:
                                print("无效的选择")
                        except ValueError:
                            print("请输入数字")
                    else:
                        print("只有1个媒体源，无法切换")
                        
                elif command == 'quit':
                    print("退出程序")
                    break
                    
                else:
                    print("无效命令，请重试")
                    
            except KeyboardInterrupt:
                print("\n程序被中断，退出...")
                break
            except Exception as e:
                print(f"错误: {e}")


if __name__ == "__main__":
    main()